<template>
	<Table ref="tableRef" :columns="data.columns" :handles="data.handles" :toolbar="data.toolbar" :query="data.query"
		@get-list="getData"></Table>
	<DialogStationUpdate ref="dialogUpdateRef"></DialogStationUpdate>
	<DialogMonitorUpdate ref="dialogMonitorRef"></DialogMonitorUpdate>
</template>

<script lang="ts" setup name="stationList">
	import Table from '@/components/table/index.vue';
	import DialogStationUpdate from '../components/dialogStationUpdate.vue';
	import DialogMonitorUpdate from '../components/dialogMonitorUpdate.vue';

	import {
		pageQueryStation,
		startStation,
		stopStation,
		delStation,
		checkEquipmentByStationId,
		EXPORT_STATION,
		allRemoteRestart,
		paramQueryBatch,
	} from '@/service/apis/pile';
	import { getCity, bntAuth, exportFile } from '@/utils/utils';
	import { STATION_STATUS_USE, STATION_VISIBLE } from '@/utils/dictionaries';
	import { queryDicByParent } from '@/service/apis/api';

	const router = useRouter();

	const tableRef = ref();
	const dialogUpdateRef = ref();
	const dialogMonitorRef = ref();

	const emit = defineEmits(['get-update']);
	onActivated(() => {
		emit('get-update', (flag : boolean) => {
			if (flag) {
				tableRef.value?.getData();
			}
		});
	});

	queryDicByParent({
		listDtos: ['stationStatus', 'stationType'],
	}).then((res : any) => {
		if (res) {
			console.log('ddd--', res);
			data.columns[4].dic = [...res.stationStatus];
			data.columns[5].dic = [...res.stationType];
			data.query[2].props.options = [...res.stationStatus];
			data.query[5].props.options = [...res.stationType];
		}
	});
	// 获取省市
	getCity().then((res : any) => {
		data.query[4].props.options = [...res];
	});

	const data = reactive({
		columns: [
			{
				prop: 'channelName',
				label: '平台运营商',
				width: 90,
			},
			{
				prop: 'stationName',
				label: '电站名称',
				width: 200,
			},
			{
				prop: 'operatorName',
				label: '运营商',
			},
			{
				prop: 'areaCodeName',
				label: '区划',
			},
			{
				prop: 'stationStatus',
				label: '运营状态',
				dic: [] as any,
			},
			{
				prop: 'stationType',
				label: '电站类型',
				dic: [] as any,
				width: 120,
			},
			// {
			// 	prop: 'bindLabelNames',
			// 	label: '绑定标签',
			// 	template: (row : any, index : number) => {
			// 		let str = '';
			// 		row.labelList?.forEach((item : any, index : number) => {
			// 			if (index === 0) {
			// 				str += `${item.labelName}`;
			// 			} else {
			// 				str += `,${item.labelName}`;
			// 			}
			// 		});
			// 		return str || '--';
			// 	},
			// },
			// {
			// 	prop: 'openExplain',
			// 	label: '开放时间',
			// },
			{
				prop: 'isMobileVisible',
				label: '移动端可见',
				dic: STATION_VISIBLE,
				width: 90,
			},
			{
				prop: 'isEnableStart',
				label: '启停状态',
				template: (row : any, index : number) => {
					return row.isEnableStart
						? `<div style="color:#01C68B;">启用</div>`
						: `<div style="color:#FA3939;">停用</div>`;
				},
			},
			{
				prop: 'freeCount',
				label: '终端工作状态(充电中/空闲/占用/离线/故障/总数)',
				templateHeader: (row : any) => {
					return '终端工作状态<br>(充电中/空闲/占用/离线/故障/总数)';
				},
				width: 240,
				template: (row : any) => {
					const line = '<span style="padding:0 5px;">/</span>';
					return `<span style="color:#5073F7;">${row.occupyChargingCount}</span>
        ${line}<span style="color:#01C68B;">${row.freeCount}</span>
        ${line}<span style="color:#FAAD14;">${row.occupyUnchargedCount}</span>
        ${line}<span style="color:#C4C4C4;">${row.offLineCount}</span>
        ${line}<span style="color:#FA3939;">${row.faultCount}</span>
        ${line}${row.connectorCount}`;
				},
			},
		],
		handles: [
			{
				label: '修改',
				permission: 'stationList.edit',
				handle: (row : any) => {
					console.log('编辑---', row);
					router.push({
						name: 'stationEdit',
						query: { id: row.id },
					});
				},
			},
			{
				label: '详情',
				handle: (row : any) => {
					console.log('复制---', row);
					router.push({
						name: 'stationDetail',
						query: { id: row.id },
					});
				},
			},
			{
				label: '停用',
				permission: 'stationList.use',
				labelFun: (row : any) => {
					return !row.isEnableStart ? '启用' : '停用';
				},
				colorFun: (row : any) => {
					return !row.isEnableStart ? '#01C68B' : '#FA3939';
				},
				handle: (row : any) => {
					checkPile(row);
				},
			},
			{
				label: '删除',
				color: '#FA3939',
				permission: 'stationList.delete',
				handle: (row : any) => {
					ElMessageBox.confirm(
						'此操作会将电站下所有设备（电桩）一起删除，是否继续删除？',
						'提示',
						{
							confirmButtonText: '确认',
							cancelButtonText: '取消',
							type: 'warning',
						}
					).then(() => {
						delStation({
							id: row.id,
						}).then((res : any) => {
							tableRef.value.getData();
						});
					});
				},
			},
			{
				label: '远程重启',
				handle: (row : any) => {
					clickRestart(row);
				},
			},
			{
				label: '远程升级',
				permission: 'stationList.update',
				handle: (row : any) => {
					dialogUpdateRef.value?.show(row);
				},
			},
			{
				label: '省监管对接',
				permission: 'stationList.abutment',
				handle: (row : any) => {
					router.push({
						name: 'regulatoryDocking',
						query: { id: row.id },
					});
				},
			},
			// {
			// 	label: '周边设备',
			// 	permission: 'stationList.device',
			// 	handle: (row : any) => {
			// 		router.push({
			// 			name: 'peripheralEquipment',
			// 			query: { id: row.id }
			// 		});
			// 	},
			// },
			{
				label: '版本更新',
				permission: 'stationList.device',
				handle: (row : any) => {
					paramQueryBatch({ stationId: row.id }).then((res : any) => {
						if (res) {
							// console.log('更新版本查询---',res);
							// tableRef.value.getData();
							if (res == 1) {
								ElMessage({
									showClose: true,
									message: '电站固件版本信息更新成功！',
									type: 'success',
								});
							}
						}
					});
				},
			},
		],
		toolbar: [
			{
				label: '新增',
				permission: 'stationList.add',
				icon: 'icon-add',
				type: 'primary',
				handle: (row : any) => {
					router.push({
						name: 'stationAdd',
					});
				},
			},
			{
				label: '导出',
				permission: 'stationList.export',
				icon: 'icon-export',
				type: 'primary',
				plain: true,
				handle: (row : any) => {
					console.log('导出---', row);
					exportFile(EXPORT_STATION, '电站列表', tableRef.value?.getForm());
				},
			},
		],
		query: [
			{
				label: '电站名称',
				prop: 'stationName',
				comName: 'input',
				props: {
					placeholder: '请输入电站名称',
				},
			},
			{
				label: '归属运营商',
				prop: 'operatorName',
				comName: 'input',
				props: {
					placeholder: '请输入归属运营商',
				},
			},
			{
				label: '运营状态',
				prop: 'stationStatus',
				comName: 'select',
				props: {
					placeholder: '请选择运营状态',
					options: [] as any,
				},
			},
			{
				label: '启停状态',
				prop: 'isEnableStart',
				comName: 'select',
				props: {
					placeholder: '请选择启停状态',
					options: STATION_STATUS_USE,
				},
			},
			{
				label: '电站城市',
				prop: 'citys',
				comName: 'cascader',
				props: {
					placeholder: '请选择电站城市',
					options: [] as any,
					// props: {
					//   checkStrictly: true,
					// },
				},
			},
			{
				label: '电站类型',
				prop: 'stationType',
				comName: 'select',
				props: {
					placeholder: '请选择电站类型',
					options: [] as any,
				},
			},
			{
				label: '平台运营商',
				prop: 'channelName',
				comName: 'input',
				props: {
					placeholder: '请输入平台运营商',
				},
			},
		],
	});

	//远程重启所有充电桩
	const clickRestart = (row : any) => {
		allRemoteRestart({ id: row.id }).then((res : any) => {
			console.log('res---', res);
			ElMessage({
				showClose: true,
				message: '远程重启指令下发成功，请稍后查看电桩状态！',
				type: 'success',
			});
		});
	};

	const getData = (page : any, search : any) => {
		const form = search.ruleForm;
		delete form.provinceCode;
		delete form.cityCode;
		if (form.citys?.length === 1) {
			form.provinceCode = form.citys[0];
		}
		if (form.citys?.length === 2) {
			form.provinceCode = form.citys[0];
			form.cityCode = form.citys[1];
		}
		pageQueryStation(form, page).then((res : any) => {
			if (res) {
				if (page.pageNo !== 1 && (!res.dataList || res.dataList?.length === 0)) {
					page.pageNo--;
					getData(page, search);
					return;
				}
				nextTick(() => {
					tableRef.value?.setTable({
						total: res.totalCount,
						table: res.dataList,
					});
				});
			}
		});
	};

	// 启动前判断桩是否可用
	const checkPile = (row : any) => {
		if (row.isEnableStart) {
			// 停用
			stationUse(row);
		} else {
			//启用
			checkEquipmentByStationId({ stationId: row.id }).then((res : any) => {
				if (res.isExist) {
					// 有电桩，提示启用
					stationUse(row);
				} else {
					ElMessageBox.confirm(
						'此电站下没有电桩，需要先新增电桩才能启用！',
						'提示',
						{
							confirmButtonText: '新增电桩',
							cancelButtonText: '取消',
							type: 'warning',
						}
					).then(() => {
						// 判断是否有新增电桩权限
						if (bntAuth('pileList.add')) {
							router.push({
								name: 'pileAdd',
								query: { stationId: row.id },
							});
						} else {
							ElMessage({
								showClose: true,
								message: '您没有新增电桩权限，请联系管理员！',
								type: 'warning',
							});
						}
					});
				}
			});
		}
	};
	// 启用/停用
	const stationUse = (row : any) => {
		const msg = !row.isEnableStart
			? '是否启用该电站？'
			: '电站停用后电站内所有电桩将不可使用，是否继续？';
		ElMessageBox.confirm(msg, '提示', {
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning',
		}).then(() => {
			if (row.isEnableStart) {
				stopStation({
					id: row.id,
				}).then((res : any) => {
					row.isEnableStart = !row.isEnableStart;
				});
			} else {
				startStation({
					id: row.id,
				}).then((res : any) => {
					row.isEnableStart = !row.isEnableStart;
				});
			}
		});
	};
</script>